<?php

namespace app\admin\controller\rate;

use app\common\controller\Backend;
use app\common\model\rate\AdminCompany;
use app\common\model\rate\CompanyRate;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use think\Validate;

/**
 * 公司信息
 *
 * @icon fa fa-circle-o
 */
class Company extends Backend
{
    
    /**
     * Company模型对象
     * @var \app\common\model\rate\Company
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\rate\Company;
        $this->view->assign("managementList", $this->model->getManagementList());
        $this->view->assign("identificationswitchList", $this->model->getIdentificationswitchList());
        $this->view->assign("serviceTypeList", $this->model->getServiceTypeList());
        $this->view->assign("isJietiList", $this->model->getIsJietiList());
        Hook::add('company_auth','app\\common\\behavior\\AdminAuth');

        $rate =  \app\common\model\rate\Area::where('is_show' , 0)->select();
        $rate_area = [];
        foreach ($rate as $k => $v) {
            $rate_area[] = ['id' => $v['id'], 'name' => $v['name']];
        }
        $this->assign('rate_area', $rate_area);
        $this->assignconfig('rate_area', $rate_area);

    }
    /**修改管理员账号*/
    public function editAdmin($ids = null) {
        $info = $this->model->get($ids);
        $admin_id = (new AdminCompany())->where('company_id', $info['id'])->value('admin_id');
        $admin = new \app\common\model\rate\Admin();
        $row = $admin->get(['id' => $admin_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($params['password']) {
                    if(!Validate::is($params['password'], '\S{6,16}')){
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function rateDetail() {
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['rate'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','concat_phone','credit_code','code','limit_money', 'max_tip']);
                $row->visible(['rate']);
                $row->getRelation('rate')->visible(['id','name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 创建企业
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $rate_c = $this->request->post('rate_c/a');
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);

                    $result = $this->model->toArray();
                    $other = [
                        'is_has_spread' => $params['is_has_spread'],
                        'rate_c' => $rate_c,
                        'company_id'   => $result['id'],
                        'code'         => $result['credit_code'],
                        'who' => 0,
                        'name' => $result['name'],
                        'email' => $result['email']
                    ];
                    //生成账号 加入权限组
                    Hook::listen('company_auth',$other);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    private function getNewArray($arr) {
        $new_sub = [];
        foreach ($arr as $k0 => $v0) {
            $new_sub[$v0['rate_area_id']] = $v0; //key值为税源地
        }

        return $new_sub;
    }
    public function edit($ids = null)
    {
        //获取税源地信息
        $companyRate = new CompanyRate();
        $rate_c = $companyRate->where('company_id', $ids)->select();
        foreach ($rate_c as $k => &$v){
            $v['name'] = \app\common\model\rate\Area::where('id', $v['rate_area_id'])->value('name');
        }

        if ($this->request->isAjax()) {
            $rate_c = collection($rate_c)->toArray();
            //如果提交数据 处理提交数据信息
            $rate_sub = $this->request->post('rate_c/a');
            $new_sub = $this->getNewArray($rate_sub);  //提交数据
            $new_rate_c = $this->getNewArray($rate_c); // 数据库原来数据

            $insert_sub = $new_sub;
            //判断之前是否存在关系 如果存在就修改 不存在就删除
            foreach ($new_rate_c as $k3 => $v3) {
                //判断是否存在于 于$rate_sub中
                if (isset($new_sub[$k3])) {
                    //存在修改
                    $companyRate->where('id', $v3['id'])->update([
                        'year_tip' => $new_sub[$k3]['year_tip'],
                        'month_tip' => $new_sub[$k3]['month_tip'],
                        'limit_money' => $new_sub[$k3]['limit_money'],
                        'evaluation_expression' => $new_sub[$k3]['evaluation_expression'],
                        'is_check' => $new_sub[$k3]['is_check']
                    ]);
                    //然后从提交数据中删除
                    unset($insert_sub[$k3]);
                } else {
                    //原来数据不存在于本次提交 需要判断企业在本税源地是否有余额 如果有余额 不能删除
                    if ($v3['money'] > 0) {
                        $this->error('企业在税源地->' . $v3['name'] . '有余额未消费完成，不能取消关系');
                    }
                    //没有余额 直接取消关系
                    $companyRate->where('id', $v3['id'])->delete();
                }
            }
            //处理完成后 把剩余的直接添加进去
            foreach ($insert_sub as $k1 => $v1) {
                $temp = [
                    'company_id' => $ids,
                    'rate_area_id' => $v1['rate_area_id'],
                    'year_tip' => $v1['year_tip'],
                    'month_tip' => $v1['month_tip'],
                    'limit_money' => $v1['limit_money'],
                    'evaluation_expression' => $v1['evaluation_expression'],
                    'is_check' => $v1['is_check'],
                    'createtime' => time()
                ];

                $companyRate->insert($temp);
            }
        }

        $this->assignconfig('rate_c', collection($rate_c)->toArray());

        return parent::edit($ids);
    }

}
